<template>
  <div class="card-drawing-analysis">
    
    <div class="overall-summary">
      <div class="summary-left">
        <div class="uid">UID: {{ UID }}</div>
        <div class="total-gold">总金数: {{ goldenLegendTotalCount }}金</div>
      </div>
      <div class="summary-right">
        <div class="total-pulls">总抽卡数: {{ drawCardTotalCount }}抽</div>
        <div class="avg-gold">平均出金数: {{ goldenLegendAvgCount }}抽</div>
      </div>
    </div>

    <div class="nav-tabs">
      <div class="tab active">卡片总结</div>
    </div>

    <div class="pools-container">
      <div class="pool-section">
        <div class="pool-header">
          <h3 class="pool-title">角色池</h3>
            <div class="pool-stats">
             <span>总抽卡: {{ characterActivityPool.totalPulls }}</span>
             <span>每UP角色: {{ getCharacterActivityAvgGoldCount() }}抽</span>
             <span>每金花费: {{ characterActivityPool.avgGoldCount }}抽</span>
             <span>出金数: {{ characterActivityPool.totalGoldCount }}</span>
           </div>
        </div>
        <div class="cards-row">
          <div class="card not-gold">
            <div class="card-content">
              <div class="question-mark">?</div>
              <div class="pull-count">{{ characterActivityPool.notGoldCount }}</div>
            </div>
          </div>
          <div 
            v-for="(record, index) in characterActivityPool.goldRecordsList" 
            :key="index"
            class="card gold"
          >
            <!-- 歪字标识 -->
            <div v-if="isResidentCharacter(record.name)" class="wai-badge">
              <img src="/wai.png" alt="歪" />
            </div>
            <div class="card-content">
              <div class="character-portrait">
                <img 
                  :src="getCharacterImageUrl(record.name)" 
                  :alt="record.name"
                  @error="handleImageError"
                />
              </div>
              <div class="pull-count">{{ record.pullCount }}</div>
            </div>
            <!-- 五星标识 -->
            <div class="stars-badge">
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
            </div>
          </div>

        </div>
      </div>

      <!-- 武器活动池 -->
      <div class="pool-section">
        <div class="pool-header">
          <h3 class="pool-title">武器池</h3>
          <div class="pool-stats">
            <span>总抽卡: {{ weaponActivityPool.totalPulls }}</span>
            <span>每UP武器: {{ weaponActivityPool.avgGoldCount }}抽</span>
            <span>出金数: {{ weaponActivityPool.totalGoldCount }}</span>
          </div>
        </div>
        <div class="cards-row">
          <div class="card not-gold">
            <div class="card-content">
              <div class="question-mark">?</div>
              <div class="pull-count">{{ weaponActivityPool.notGoldCount }}</div>
            </div>
          </div>
          <div 
            v-for="(record, index) in weaponActivityPool.goldRecordsList" 
            :key="index"
            class="card gold"
          >
            <div class="card-content">
              <div class="weapon-portrait">
                <img 
                  :src="getWeaponImageUrl(record.name)" 
                  :alt="record.name"
                  @error="handleImageError"
                />
              </div>
              <div class="pull-count">{{ record.pullCount }}</div>
            </div>
            <!-- 五星标识 -->
            <div class="stars-badge">
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 角色常驻池 -->
      <div class="pool-section">
        <div class="pool-header">
          <h3 class="pool-title">常驻角色池</h3>
          <div class="pool-stats">
            <span>总抽卡: {{ characterResidentPool.totalPulls }}</span>
            <span>每金花费: {{ characterResidentPool.avgGoldCount }}抽</span>
            <span>出金数: {{ characterResidentPool.totalGoldCount }}</span>
          </div>
        </div>
        <div class="cards-row">
          <div class="card not-gold">
            <div class="card-content">
              <div class="question-mark">?</div>
              <div class="pull-count">{{ characterResidentPool.notGoldCount }}</div>
            </div>
          </div>
          <div 
            v-for="(record, index) in characterResidentPool.goldRecordsList" 
            :key="index"
            class="card gold"
          >
            <div class="card-content">
              <div class="character-portrait">
                <img 
                  :src="getCharacterImageUrl(record.name)" 
                  :alt="record.name"
                  @error="handleImageError"
                />
              </div>
              <div class="pull-count">{{ record.pullCount }}</div>
            </div>
            <!-- 五星标识 -->
            <div class="stars-badge">
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 武器常驻池 -->
      <div class="pool-section">
        <div class="pool-header">
          <h3 class="pool-title">常驻武器池</h3>
          <div class="pool-stats">
            <span>总抽卡: {{ weaponResidentPool.totalPulls }}</span>
            <span>每金花费: {{ weaponResidentPool.avgGoldCount }}抽</span>
            <span>出金数: {{ weaponResidentPool.totalGoldCount }}</span>
          </div>
        </div>
        <div class="cards-row">
          <div class="card not-gold">
            <div class="card-content">
              <div class="question-mark">?</div>
              <div class="pull-count">{{ weaponResidentPool.notGoldCount }}</div>
            </div>
          </div>
          <div 
            v-for="(record, index) in weaponResidentPool.goldRecordsList" 
            :key="index"
            class="card gold"
          >
            <div class="card-content">
              <div class="weapon-portrait">
                <img 
                  :src="getWeaponImageUrl(record.name)" 
                  :alt="record.name"
                  @error="handleImageError"
                />
              </div>
              <div class="pull-count">{{ record.pullCount }}</div>
            </div>
            <!-- 五星标识 -->
            <div class="stars-badge">
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
              <div class="star"><img src="/star.png" alt="★" /></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { imgUrlApi } from '../services/imgUrl';

const props = defineProps({
  data: {
    type: Object,
    required: true
  }
});


// 通用的池子数据解析函数
function parsePoolData(data) {
  return {
    totalPulls: parseInt(data.totalPulls) || 0,
    avgGoldCount: parseInt(data.avgGoldCount) || 0,
    totalGoldCount: parseInt(data.totalGoldCount) || 0,
    notGoldCount: parseInt(data.notGoldCount) || 0,
    goldRecordsList: Array.isArray(data.goldRecordsList) ? data.goldRecordsList : []
  };
}

const analysisData = computed(() => {
  const data = props.data;
  if (typeof data === 'string') {
    try {
      // 尝试解析服务端返回的复杂字符串格式
      let dataStr = data;
      
      // 移除开头和结尾的引号
      if (dataStr.startsWith('"') && dataStr.endsWith('"')) {
        dataStr = dataStr.slice(1, -1);
      }
      
      // 处理转义字符
      dataStr = dataStr.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
      
      // 尝试JSON解析
      try {
        const result = JSON.parse(dataStr);
        console.log('JSON解析成功:', result);
        return result;
      } catch (jsonError) {
        console.log('JSON解析失败，尝试手动解析:', jsonError);
        // 手动解析复杂的字符串格式
        return parseComplexString(dataStr);
      }
    } catch (error) {
      console.error('解析抽卡数据失败:', error);
      return {};
    }
  }
  return data;
});

// 手动解析复杂字符串格式的函数
function parseComplexString(str) {
  const result = {};
  
  // 移除最外层的大括号
  str = str.replace(/^\{|\}$/g, '');
  
  // 分割顶级字段
  const topLevelParts = splitByComma(str);
  
  topLevelParts.forEach(part => {
    // 查找冒号位置（支持英文冒号和中文冒号）
    const colonIndex = part.indexOf(':');
    const chineseColonIndex = part.indexOf('：');
    const finalColonIndex = colonIndex > 0 ? colonIndex : chineseColonIndex;
    
    if (finalColonIndex > 0) {
      const key = part.substring(0, finalColonIndex).trim();
      const value = part.substring(finalColonIndex + 1).trim();
      
      if (value.startsWith('{') && value.endsWith('}')) {
        // 这是一个对象
        result[key] = parseObjectString(value);
      } else if (!isNaN(value)) {
        // 这是一个数字
        result[key] = parseFloat(value);
      } else {
        // 这是一个字符串
        result[key] = value;
      }
    }
  });
  console.log('手动解析结果:', result);
  return result;
}

// 解析对象字符串
function parseObjectString(str) {
  const result = {};
  
  // 移除最外层的大括号
  str = str.replace(/^\{|\}$/g, '');
  
  // 分割字段
  const parts = splitByComma(str);
  
  parts.forEach(part => {
    // 查找冒号位置（支持英文冒号和中文冒号）
    const colonIndex = part.indexOf(':');
    const chineseColonIndex = part.indexOf('：');
    const finalColonIndex = colonIndex > 0 ? colonIndex : chineseColonIndex;
    
    if (finalColonIndex > 0) {
      const key = part.substring(0, finalColonIndex).trim();
      const value = part.substring(finalColonIndex + 1).trim();
      
      if (value.startsWith('[') && value.endsWith(']')) {
        // 这是一个数组
        result[key] = parseArrayString(value);
      } else if (value.startsWith('{') && value.endsWith('}')) {
        // 这是一个嵌套对象
        result[key] = parseObjectString(value);
      } else if (!isNaN(value)) {
        // 这是一个数字
        result[key] = parseFloat(value);
      } else {
        // 这是一个字符串
        result[key] = value;
      }
    }
  });
  
  return result;
}

// 解析数组字符串
function parseArrayString(str) {
  const result = [];
  
  // 移除最外层的中括号
  str = str.replace(/^\[|\]$/g, '');
  
  if (str.trim() === '') {
    return result;
  }
  
  // 分割数组元素
  const parts = splitByComma(str);
  
  parts.forEach(part => {
    part = part.trim();
    if (part.startsWith('{') && part.endsWith('}')) {
      // 这是一个对象
      result.push(parseObjectString(part));
    } else if (!isNaN(part)) {
      // 这是一个数字
      result.push(parseFloat(part));
    } else {
      // 这是一个字符串
      result.push(part);
    }
  });
  
  return result;
}

// 智能分割逗号，考虑嵌套结构
function splitByComma(str) {
  const result = [];
  let current = '';
  let braceCount = 0;
  let bracketCount = 0;
  
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    
    if (char === '{') {
      braceCount++;
    } else if (char === '}') {
      braceCount--;
    } else if (char === '[') {
      bracketCount++;
    } else if (char === ']') {
      bracketCount--;
    } else if (char === ',' && braceCount === 0 && bracketCount === 0) {
      result.push(current.trim());
      current = '';
      continue;
    }
    
    current += char;
  }
  
  if (current.trim()) {
    result.push(current.trim());
  }
  
  return result;
}

/**
 * 使用 computed 计算属性保证页面值及时刷新，而不会出现页面不刷新导致值相加
 */
 const UID = computed(()=>{
  return analysisData.value.UID;
})

const goldenLegendTotalCount = computed(()=>{
  return analysisData.value.goldenLegendTotalCount;
})

const drawCardTotalCount = computed(()=>{
  return analysisData.value.drawCardTotalCount;
})

const goldenLegendAvgCount = computed(()=>{
  return analysisData.value.goldenLegendAvgCount;
})

//五个常驻五星角色角色
const residentCharacters = ["安可","鉴心","凌阳","维里奈","卡卡罗"];
//判断是否是常驻五星角色
function isResidentCharacter(name) {
  return residentCharacters.includes(name);
}

//角色活动池参数
const characterActivityPool = computed(() => {
  const data = analysisData.value.characterActivityPoolVO || {};
  return parsePoolData(data);
});

const weaponActivityPool = computed(() => {
  const data = analysisData.value.weaponActivityPoolVO || {};
  return parsePoolData(data);
});

const characterResidentPool = computed(() => {
  const data = analysisData.value.characterResidentPoolVO || {};
  return parsePoolData(data);
});

const weaponResidentPool = computed(() => {
  const data = analysisData.value.weaponResidentPoolVO || {};
  return parsePoolData(data);
});

// 图片URL映射存储
const characterImageMap = ref(new Map());
const weaponImageMap = ref(new Map());

// 获取角色图片URL
const getCharacterImageUrl = (characterName) => {
  return characterImageMap.value.get(characterName) || '/default-character.png';
};

// 获取武器图片URL
const getWeaponImageUrl = (weaponName) => {
  return weaponImageMap.value.get(weaponName) || '/default-weapon.png';
};

// 图片加载失败处理
const handleImageError = (event) => {
  const img = event.target;
  if (img.src.includes('character')) {
    img.src = '/default-character.png';
  } else if (img.src.includes('weapon')) {
    img.src = '/default-weapon.png';
  }
};

// 计算每活动角色花费的抽卡数
const getCharacterActivityAvgGoldCount = () => {
  const totalPulls = characterActivityPool.value.totalPulls;
  const notGoldCount = characterActivityPool.value.notGoldCount;
  const totalGoldCount = characterActivityPool.value.totalGoldCount;
  
  // 获取常驻五星角色的出金记录
  const residentGoldRecords = characterActivityPool.value.goldRecordsList.filter(record => 
    isResidentCharacter(record.name)
  );
  
  // 计算常驻五星角色花费的抽卡数
  const residentGoldPulls = residentGoldRecords.reduce((sum, record) => sum + record.pullCount, 0);
  
  // 计算常驻五星角色的出金数
  const residentGoldCount = residentGoldRecords.length;
  
  // 计算活动角色的出金数
  const activityGoldCount = totalGoldCount - residentGoldCount;
  
  // 如果活动角色出金数为0，返回0
  if (activityGoldCount <= 0) {
    return 0;
  }
  
  // 计算活动角色花费的抽卡数
  // （总抽卡数 - 未出金数）/ 活动角色出金数
  const activityPulls = totalPulls - notGoldCount;
  
  // 计算每活动角色花费的抽卡数
  const avgGoldCount = activityPulls / activityGoldCount;
  
  return Math.round(avgGoldCount * 100) / 100; // 保留两位小数
};

// 获取角色图片URL
const fetchCharacterImages = async () => {
  try {
    const characterNames = [
      ...characterActivityPool.value.goldRecordsList.map(item => item.name),
      ...characterResidentPool.value.goldRecordsList.map(item => item.name)
    ];
    
    if (characterNames.length > 0) {
      const urlMap = await imgUrlApi.getCharacterURL(characterNames);
      characterImageMap.value = urlMap;
    }
  } catch (error) {
    console.error('获取角色图片失败:', error);
  }
};

// 获取武器图片URL
const fetchWeaponImages = async () => {
  try {
    const weaponNames = [
      ...weaponActivityPool.value.goldRecordsList.map(item => item.name),
      ...weaponResidentPool.value.goldRecordsList.map(item => item.name)
    ];
    
    if (weaponNames.length > 0) {
      const urlMap = await imgUrlApi.getWeaponURL(weaponNames);
      weaponImageMap.value = urlMap;
    }
  } catch (error) {
    console.error('获取武器图片失败:', error);
  }
};

// 监听数据变化，自动获取图片
watch([characterActivityPool, characterResidentPool, weaponActivityPool, weaponResidentPool], async () => {
  await Promise.all([
    fetchCharacterImages(),
    fetchWeaponImages()
  ]);
}, { immediate: true });


</script>

<style scoped>
.card-drawing-analysis {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  border-radius: 16px;
  padding: 20px;
  color: white;
  font-family: 'Arial', sans-serif;
  min-height: 400px;
}

.overall-summary {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.summary-left, .summary-right {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.uid {
  font-size: 16px;
  font-weight: 600;
  color: #e0e0e0;
}

.total-gold, .total-pulls, .avg-gold {
  font-size: 14px;
  color: #b0b0b0;
}

.nav-tabs {
  display: flex;
  gap: 0;
  margin-bottom: 24px;
}

.tab {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px 8px 0 0;
  cursor: pointer;
  font-size: 14px;
}

.tab.active {
  background: rgba(100, 150, 255, 0.3);
  border-bottom: 2px solid #64a5ff;
}

.pools-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.pool-section {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.pool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pool-title {
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
  margin: 0;
}

.pool-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #b0b0b0;
}

.cards-row {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.card {
  width: 80px;
  height: 100px;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  position: relative; /* 为歪字标识定位 */
}

/* 歪字标识样式 */
.wai-badge {
  position: absolute;
  right: 2px;
  z-index: 10;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wai-badge img {
  width: 30px;
  height: 30px;
  object-fit: contain;
}

/* 五星标识样式 */
.stars-badge {
  position: absolute;
  bottom: 18px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  z-index: 5;
}

.star {
  display: flex;
  align-items: center;
  justify-content: center;
}

.star img {
  width: 15px;
  height: 15px;
  object-fit: contain;
}

.card.not-gold {
  background: linear-gradient(135deg, #4a4a4a 0%, #2a2a2a 100%);
}

.card.gold {
  background: url(https://web-static.kurobbs.com/resource/wiki/prod/assets/type-large-figure-bg-normal-mc-d09fa597.png) no-repeat top center / 100% 100%;
}


.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
  padding: 8px;
  text-align: center;
}

.question-mark {
  font-size: 32px;
  font-weight: bold;
  color: #ffffff;
  margin-top: 20px;
}

.character-portrait, .weapon-portrait {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  margin-bottom: 4px;
  position: relative;
  overflow: hidden;
}

.character-portrait img, .weapon-portrait img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.pull-count {
  font-size: 12px;
  font-weight: 600;
  /* 字体颜色 */
  color: #ffffff;
  text-align: center;
}

.test-section {
  text-align: center;
  margin-bottom: 20px;
}

.test-button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.test-button:hover {
  background-color: #45a049;
}
</style>
